<!-- src/views/Usage.vue -->
<template>
  <div class="usage-page">
    <!-- 顶部导航栏 -->
    <header class="dashboard-header">
      <div class="header-left">
        <h1 class="logo">🌐 VPN Manager</h1>
        <nav class="nav-menu">
          <router-link to="/dashboard" class="nav-item" :class="{ active: $route.path === '/dashboard' }">
            仪表板
          </router-link>
          <router-link to="/subscription" class="nav-item" :class="{ active: $route.path === '/subscription' }">
            订阅管理
          </router-link>
          <router-link to="/nodes" class="nav-item" :class="{ active: $route.path === '/nodes' }">
            节点列表
          </router-link>
          <router-link to="/usage" class="nav-item" :class="{ active: $route.path === '/usage' }">
            使用记录
          </router-link>
        </nav>
      </div>
      <div class="header-right">
        <div class="user-menu">
          <span class="user-name">{{ authStore.user?.email }}</span>
          <div class="user-avatar">
            {{ authStore.user?.email?.charAt(0).toUpperCase() }}
          </div>
          <button @click="logout" class="logout-btn">退出</button>
        </div>
      </div>
    </header>

    <div class="page-content">
      <header class="page-header">
        <h1>📊 使用记录</h1>
        <p>查看您的VPN使用情况和流量统计</p>
      </header>

      <!-- 统计概览 -->
      <div class="stats-grid">
        <div class="stat-card total-usage">
          <div class="stat-icon">📈</div>
          <div class="stat-content">
            <h3>总使用流量</h3>
            <p class="stat-value">{{ formatTraffic(totalUsage) }}</p>
            <p class="stat-period">累计使用</p>
          </div>
        </div>

        <div class="stat-card current-period">
          <div class="stat-icon">⏰</div>
          <div class="stat-content">
            <h3>本月使用</h3>
            <p class="stat-value">{{ formatTraffic(currentMonthUsage) }}</p>
            <p class="stat-period">当前周期</p>
          </div>
        </div>

        <div class="stat-card daily-avg">
          <div class="stat-icon">📅</div>
          <div class="stat-content">
            <h3>日均使用</h3>
            <p class="stat-value">{{ formatTraffic(dailyAverage) }}</p>
            <p class="stat-period">平均每天</p>
          </div>
        </div>

        <div class="stat-card remaining">
          <div class="stat-icon">🎯</div>
          <div class="stat-content">
            <h3>剩余流量</h3>
            <p class="stat-value">{{ formatTraffic(remainingTraffic) }}</p>
            <p class="stat-period">当前订阅</p>
          </div>
        </div>
      </div>

      <!-- 流量图表 -->
      <div class="chart-section">
        <div class="card">
          <div class="card-header">
            <h2>📈 流量使用趋势</h2>
            <div class="chart-controls">
              <select v-model="selectedPeriod" @change="loadUsageData">
                <option value="7">最近7天</option>
                <option value="30">最近30天</option>
                <option value="90">最近3个月</option>
              </select>
            </div>
          </div>
          <div class="card-content">
            <div class="chart-container">
              <div v-if="usageData.length === 0" class="empty-chart">
                <div class="empty-icon">📊</div>
                <p>暂无使用数据</p>
              </div>
              <div v-else class="chart">
                <div class="chart-bars">
                  <div
                      v-for="(item, index) in usageData"
                      :key="index"
                      class="bar-container"
                  >
                    <div class="bar-wrapper">
                      <div
                          class="bar"
                          :style="{ height: getBarHeight(item.usage_mb) + '%' }"
                          :class="getBarClass(item.usage_mb)"
                      ></div>
                    </div>
                    <div class="bar-label">
                      {{ formatDateLabel(item.date) }}
                    </div>
                    <div class="bar-value">
                      {{ formatTraffic(item.usage_mb) }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 详细使用记录 -->
      <div class="records-section">
        <div class="card">
          <div class="card-header">
            <h2>📋 详细记录</h2>
            <div class="filter-controls">
              <select v-model="pageSize">
                <option value="10">每页10条</option>
                <option value="20">每页20条</option>
                <option value="50">每页50条</option>
              </select>
            </div>
          </div>
          <div class="card-content">
            <div class="table-container">
              <table class="usage-table">
                <thead>
                <tr>
                  <th>日期</th>
                  <th>使用时长</th>
                  <th>上传流量</th>
                  <th>下载流量</th>
                  <th>总流量</th>
                  <th>连接节点</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="record in paginatedRecords" :key="record.id">
                  <td>{{ formatDateTime(record.created_at) }}</td>
                  <td>{{ formatDuration(record.duration_seconds) }}</td>
                  <td>{{ formatTraffic(record.upload_mb) }}</td>
                  <td>{{ formatTraffic(record.download_mb) }}</td>
                  <td class="total-traffic">
                    {{ formatTraffic(record.upload_mb + record.download_mb) }}
                  </td>
                  <td>
                    <span class="node-tag">{{ record.node?.name || '未知节点' }}</span>
                  </td>
                </tr>
                </tbody>
              </table>

              <div v-if="usageRecords.length === 0" class="empty-records">
                <div class="empty-icon">📝</div>
                <p>暂无使用记录</p>
              </div>
            </div>

            <!-- 分页控件 -->
            <div v-if="usageRecords.length > 0" class="pagination">
              <button
                  @click="prevPage"
                  :disabled="currentPage === 1"
                  class="pagination-btn"
              >
                上一页
              </button>
              <span class="pagination-info">
                第 {{ currentPage }} 页，共 {{ totalPages }} 页
              </span>
              <button
                  @click="nextPage"
                  :disabled="currentPage === totalPages"
                  class="pagination-btn"
              >
                下一页
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth'
import { getUsageHistory } from '@/api/vpn'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const usageRecords = ref([])
const usageData = ref([])
const selectedPeriod = ref('7')
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// 计算属性
const totalUsage = computed(() => {
  return usageRecords.value.reduce((total, record) =>
      total + record.upload_mb + record.download_mb, 0)
})

const currentMonthUsage = computed(() => {
  const currentMonth = new Date().getMonth()
  const currentYear = new Date().getFullYear()

  return usageRecords.value
      .filter(record => {
        const recordDate = new Date(record.created_at)
        return recordDate.getMonth() === currentMonth &&
            recordDate.getFullYear() === currentYear
      })
      .reduce((total, record) => total + record.upload_mb + record.download_mb, 0)
})

const dailyAverage = computed(() => {
  if (usageRecords.value.length === 0) return 0
  const days = new Set(usageRecords.value.map(record =>
      record.created_at.split('T')[0])).size
  return days > 0 ? totalUsage.value / days : 0
})

const remainingTraffic = computed(() => {
  if (!authStore.currentSubscription) return 0
  const total = authStore.currentSubscription.subscription?.traffic_mb || 0
  const used = authStore.currentSubscription.used_traffic_mb || 0
  return Math.max(0, total - used)
})

const paginatedRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return usageRecords.value.slice(start, end)
})

const totalPages = computed(() => {
  return Math.ceil(usageRecords.value.length / pageSize.value)
})

// 生命周期
onMounted(async () => {
  await loadUsageData()
})

// 方法
const loadUsageData = async () => {
  if (!authStore.user) return

  loading.value = true
  try {
    const response = await getUsageHistory(authStore.user.id, {
      days: selectedPeriod.value
    })

    if (response.data && Array.isArray(response.data)) {
      usageRecords.value = response.data
    } else {
      // 使用模拟数据
      usageRecords.value = getMockUsageRecords()
    }

    // 生成图表数据
    generateChartData()
  } catch (error) {
    console.error('加载使用记录失败:', error)
    // 使用模拟数据
    usageRecords.value = getMockUsageRecords()
    generateChartData()
    alert('加载使用记录失败，使用模拟数据展示')
  } finally {
    loading.value = false
  }
}

// 模拟使用记录数据
const getMockUsageRecords = () => {
  const records = []
  const now = new Date()

  for (let i = 0; i < 30; i++) {
    const date = new Date(now)
    date.setDate(date.getDate() - i)

    records.push({
      id: i + 1,
      created_at: date.toISOString(),
      duration_seconds: Math.floor(Math.random() * 3600) + 1800, // 30分钟到1.5小时
      upload_mb: Math.floor(Math.random() * 100) + 10,
      download_mb: Math.floor(Math.random() * 500) + 50,
      node: {
        name: ['北京节点', '香港节点', '美国节点'][Math.floor(Math.random() * 3)]
      }
    })
  }

  return records
}

const generateChartData = () => {
  const days = parseInt(selectedPeriod.value)
  const data = []

  for (let i = days - 1; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    const dateStr = date.toISOString().split('T')[0]

    const dayUsage = usageRecords.value
        .filter(record => record.created_at.startsWith(dateStr))
        .reduce((total, record) => total + record.upload_mb + record.download_mb, 0)

    data.push({
      date: dateStr,
      usage_mb: dayUsage
    })
  }

  usageData.value = data
}

const getBarHeight = (usage) => {
  const maxUsage = Math.max(...usageData.value.map(item => item.usage_mb))
  if (maxUsage === 0) return 0
  return Math.min(100, (usage / maxUsage) * 100)
}

const getBarClass = (usage) => {
  if (usage === 0) return 'zero'
  const maxUsage = Math.max(...usageData.value.map(item => item.usage_mb))
  const percentage = usage / maxUsage
  if (percentage < 0.3) return 'low'
  if (percentage < 0.7) return 'medium'
  return 'high'
}

const logout = () => {
  authStore.clearToken()
  router.push('/login')
}

const formatTraffic = (mb) => {
  if (!mb) return '0 MB'
  if (mb < 1024) return `${Math.round(mb)} MB`
  return `${(mb / 1024).toFixed(2)} GB`
}

const formatDateLabel = (dateStr) => {
  const date = new Date(dateStr)
  return `${date.getMonth() + 1}/${date.getDate()}`
}

const formatDateTime = (dateStr) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

const formatDuration = (seconds) => {
  if (!seconds) return '0秒'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  if (hours > 0) {
    return `${hours}小时${minutes}分`
  } else if (minutes > 0) {
    return `${minutes}分${secs}秒`
  } else {
    return `${secs}秒`
  }
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}
</script>

<style scoped>
.usage-page {
  min-height: 100vh;
  background: #f5f7fa;
}

/* 顶部导航样式 */
.dashboard-header {
  background: white;
  padding: 0 30px;
  border-bottom: 1px solid #e1e5e9;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 64px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 40px;
}

.logo {
  font-size: 20px;
  font-weight: 700;
  color: #1890ff;
  margin: 0;
}

.nav-menu {
  display: flex;
  gap: 30px;
}

.nav-item {
  text-decoration: none;
  color: #666;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.3s;
}

.nav-item.active {
  background: #1890ff;
  color: white;
}

.nav-item:hover:not(.active) {
  background: #f0f0f0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-menu {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-name {
  color: #333;
  font-weight: 500;
}

.user-avatar {
  width: 36px;
  height: 36px;
  background: #1890ff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.logout-btn {
  padding: 6px 12px;
  border: 1px solid #dc3545;
  background: white;
  color: #dc3545;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.logout-btn:hover {
  background: #dc3545;
  color: white;
}

.page-content {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 32px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
}

/* 统计网格 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.stat-card {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  font-size: 36px;
}

.stat-content h3 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
  font-weight: normal;
}

.stat-value {
  margin: 0 0 4px 0;
  font-size: 24px;
  font-weight: 700;
  color: #333;
}

.stat-period {
  margin: 0;
  font-size: 12px;
  color: #999;
}

/* 图表区域 */
.chart-section {
  margin-bottom: 32px;
}

.card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.card-header {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.chart-controls select,
.filter-controls select {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  background: white;
  color: #333;
}

.card-content {
  padding: 24px;
}

.chart-container {
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-chart {
  text-align: center;
  color: #666;
}

.empty-chart .empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.chart {
  width: 100%;
}

.chart-bars {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  height: 200px;
  padding: 20px 0;
}

.bar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  margin: 0 4px;
}

.bar-wrapper {
  height: 150px;
  width: 20px;
  display: flex;
  align-items: flex-end;
  margin-bottom: 8px;
}

.bar {
  width: 100%;
  border-radius: 4px 4px 0 0;
  transition: height 0.3s;
}

.bar.zero {
  background: #f0f0f0;
}

.bar.low {
  background: linear-gradient(to top, #52c41a, #73d13d);
}

.bar.medium {
  background: linear-gradient(to top, #faad14, #ffc53d);
}

.bar.high {
  background: linear-gradient(to top, #ff4d4f, #ff7875);
}

.bar-label {
  font-size: 10px;
  color: #666;
  text-align: center;
}

.bar-value {
  font-size: 10px;
  color: #333;
  font-weight: 500;
  margin-top: 4px;
}

/* 记录表格 */
.records-section {
  margin-bottom: 32px;
}

.table-container {
  overflow-x: auto;
}

.usage-table {
  width: 100%;
  border-collapse: collapse;
}

.usage-table th,
.usage-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.usage-table th {
  background: #fafafa;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.usage-table td {
  color: #666;
  font-size: 14px;
}

.total-traffic {
  font-weight: 600;
  color: #333;
}

.node-tag {
  background: #f0f8ff;
  color: #1890ff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.empty-records {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-records .empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 24px;
  padding: 16px;
}

.pagination-btn {
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  background: white;
  color: #333;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.pagination-btn:hover:not(:disabled) {
  border-color: #1890ff;
  color: #1890ff;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}
</style>